package fr.sedoo.metadata.client.ui.view.common;

import java.util.ArrayList;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.TabLayoutPanel;

import fr.sedoo.metadata.client.ui.widget.field.api.IsDisplay;
import fr.sedoo.metadata.client.ui.widget.field.api.IsEditor;
import fr.sedoo.metadata.shared.domain.MetadataDTO;

public class MetadataTabPanel extends TabLayoutPanel implements IsDisplay, IsEditor {
	public final static double DEFAULT_HEIGHT = 40;

	private ArrayList<AbstractTab> tabs = new ArrayList<AbstractTab>();

	private String mode;

	public MetadataTabPanel() {
		this(DEFAULT_HEIGHT, Unit.PX);
	}

	public MetadataTabPanel(double barHeight, Unit barUnit) {
		super(barHeight, barUnit);
		addStyleName("metadataTabPanel");
		reset();
	}

	public void addTab(AbstractTab tab, String title) {
		add(tab, title);
		tabs.add(tab);
	}

	/**
	 * Some tabs need their content to be created at the moment they are
	 * selected. For instance , with Google Maps layers, geographical tabs are
	 * shifted if created while hidden. This function activate the selection
	 * handler that informs tabs their are selected This function must not be
	 * called before tabs have been added.
	 */
	public void activateSelectionHandler() {
		addSelectionHandler(new SelectionHandler<Integer>() {
			@Override
			public void onSelection(SelectionEvent<Integer> event) {
				AbstractTab tab = tabs.get(event.getSelectedItem());
				tab.isSelected(getMode());

			}
		});
	}

	@Override
	public void edit(MetadataDTO dto) {
		setMode(IsEditor.EDIT_MODE);
		reset();
		MetadataDTO metadata = (MetadataDTO) dto;
		for (AbstractTab tab : tabs) {
			tab.edit(metadata);
		}
	}

	@Override
	public void display(MetadataDTO dto) {
		setMode(IsDisplay.DISPLAY_MODE);
		reset();
		MetadataDTO metadata = (MetadataDTO) dto;
		for (AbstractTab tab : tabs) {
			tab.display(metadata);
		}
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	@Override
	public void reset() {
		for (AbstractTab tab : tabs) {
			tab.reset();
		}
	}

	@Override
	public void flush(MetadataDTO metadataDTO) {
		for (AbstractTab tab : tabs) {
			tab.flush(metadataDTO);
		}
	}

}
